package com.seafood.controller;

import com.seafood.common.PageResult;
import com.seafood.common.Result;
import com.seafood.dto.CreateOrderDTO;
import com.seafood.dto.OrderDTO;
import com.seafood.dto.OrderStatisticsDTO;
import com.seafood.entity.Order;
import com.seafood.service.AdminUserService;
import com.seafood.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 订单控制器
 */
@Tag(name = "订单管理", description = "订单相关API")
@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
@Validated
public class OrderController {
    
    private final OrderService orderService;
    private final AdminUserService userService;
    /**
     * 创建订单
     */
    @Operation(summary = "创建订单", description = "创建新订单")
    @PostMapping
    public Result<OrderDTO> createOrder(@Valid @RequestBody CreateOrderDTO createOrderDTO,
                                       Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            OrderDTO order = orderService.createOrder(userId, createOrderDTO);
            return Result.success("订单创建成功", order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     */
    @Operation(summary = "获取订单详情", description = "根据订单ID获取订单详情")
    @GetMapping("/{id}")
    public Result<OrderDTO> getOrderById(@PathVariable Long id) {
        try {
            OrderDTO order = orderService.getOrderById(id);
            return Result.success(order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户订单列表
     */
    @Operation(summary = "获取用户订单列表", description = "获取当前用户的订单列表")
    @GetMapping("/my")
    public Result<PageResult<OrderDTO>> getMyOrders(@RequestParam(defaultValue = "1") Integer page,
                                                   @RequestParam(defaultValue = "10") Integer size,
                                                   Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            PageResult<OrderDTO> orders = orderService.getUserOrders(userId, page, size);
            return Result.success(orders);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有订单列表（管理员）
     */
    @Operation(summary = "获取所有订单列表", description = "管理员获取所有订单列表")
    @GetMapping("/all")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<PageResult<OrderDTO>> getAllOrders(@RequestParam(defaultValue = "1") Integer page,
                                                    @RequestParam(defaultValue = "10") Integer size) {
        try {
            PageResult<OrderDTO> orders = orderService.getAllOrders(page, size);
            return Result.success(orders);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户订单统计信息
     */
    @Operation(summary = "获取用户订单统计", description = "获取当前用户的订单统计信息")
    @GetMapping("/stats/my")
    public Result<OrderStatisticsDTO> getMyOrderStats(Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            OrderStatisticsDTO stats = orderService.getUserOrderStats(userId);
            return Result.success(stats);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新订单状态
     */
    @Operation(summary = "更新订单状态", description = "更新订单状态（管理员）")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<OrderDTO> updateOrderStatus(@PathVariable Long id,
                                             @RequestParam Order.OrderStatus status) {
        try {
            OrderDTO order = orderService.updateOrderStatus(id, status);
            return Result.success("订单状态更新成功", order);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @Operation(summary = "取消订单", description = "取消订单")
    @PutMapping("/{id}/cancel")
    public Result<String> cancelOrder(@PathVariable Long id,
                                     Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            orderService.cancelOrder(id, userId);
            return Result.success("订单取消成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从认证信息中获取用户ID
     */
    private Long getUserIdFromAuth(Authentication authentication) {
        // 假设用户名就是用户ID，实际项目中可能需要查询用户表
        try {
            String name = authentication.getName();
            Long userIdByName = userService.getUserIdByName(name);
            return userIdByName;
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的用户认证信息");
        }
    }
}